package logic

import (
	"context"
	"fmt"

	"longbri/rpc/internal/svc"
	"longbri/rpc/pb/dashboard"

	"github.com/zeromicro/go-zero/core/logx"
)

type RankListLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewRankListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *RankListLogic {
	return &RankListLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *RankListLogic) RankList(in *dashboard.RankListReq) (*dashboard.RankListRsp, error) {
	// todo: add your logic here and delete this line
	fmt.Println(in.String())
	var perPageCount = in.PerPageCount
	if perPageCount <= 0 {
		perPageCount = 100
	}

	if perPageCount > 1000 {
		perPageCount = 1000
	}

	var startPos = int(in.CurPageNum * perPageCount)

	count, err := l.svcCtx.RankListModel.GetCount(l.ctx, in.StartDate, in.EndDate, int(in.UpDivChange), int(in.MarketValStart), int(in.MarKetValEnd), int(in.UpRation), int(in.ChangeRatio))
	fmt.Printf("GetCount:%d MarketValStart:%d\n", count, in.MarketValStart)
	if err != nil {
		return nil, err
	}

	rsp, err := l.svcCtx.RankListModel.Find(l.ctx, in.StartDate, in.EndDate, startPos, int(perPageCount), int(in.UpDivChange), int(in.MarketValStart), int(in.MarKetValEnd), int(in.UpRation), int(in.ChangeRatio))
	if err != nil {
		return nil, err
	}

	fmt.Printf("size:%d \n", len(rsp))

	var infos []*dashboard.RankListInfo
	for i := 0; i < len(rsp); i++ {
		tmp := rsp[i]
		infos = append(infos, &dashboard.RankListInfo{
			Date:                   tmp.Date.Time.Format("2006-01-02"),
			Code:                   tmp.Code.String,
			Name:                   tmp.Name.String,
			MarketVal:              tmp.MarketVal.String,
			ChangeRatio:            tmp.ChangeRatio.String,
			TradeChangeRatio:       tmp.TradeChangeRatio.String,
			CirculationMarketValue: tmp.CirculationMarketValue.String,
			TotalShares:            tmp.TotalShares.String,
			CirculationShares:      tmp.CirculationShares.String,
			PriceNominal:           tmp.PriceNominal.String,
			TradeTrunover:          tmp.TradeTrunover.String,
			TradeVolumn:            tmp.TradeVolumn.String,
			PriceAmplitude:         tmp.PriceAmplitude.String,
		})
	}
	TotalCount := int32(count) / perPageCount
	if int32(count)%perPageCount > 0 {
		TotalCount++
	}

	return &dashboard.RankListRsp{
		RankInfos:  infos,
		TotalCount: int32(TotalCount),
		CurPageNum: in.CurPageNum,
	}, nil
}
